<?php

namespace App\Admin\Forms;

use EasyWeChat\Factory;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;

class WechatMenu extends Form
{
    /**
     * The form title.
     *
     * @var string
     */
    public $title = '发布菜单';

    /**
     * Handle the form request.
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request)
    {
        //dump($request->all());
        $menuList = \App\Models\WechatMenu::query()->where('is_del', 0)->where('pid', 0)
            ->where('state', 1)->with(['children'])->orderBy('sort')->get();
        if ($menuList->isEmpty()) {
            admin_error('请先添加菜单');
            return back();
        }
        $menuList = $menuList->toArray();
        $menuArr = [];
        foreach ($menuList as $item) {
            $childArr = [];
            $children = $item['children'];
            $parentTitle = $item['title'];
            if (!empty($children)) {
                $temp = [
                    'name' => $parentTitle,
                ];
                foreach ($children as $child) {
                    if ($child['type'] == 1) {
                        $eventKey = 'custom_key_' . $child['id'];
                        $childArr[] = [
                            'type' => 'click',
                            'name' => $child['title'],
                            'key'  => $eventKey,
                        ];
                        \App\Models\WechatMenu::query()->where('id', $child['id'])->update([
                            'custom_key' => $eventKey,
                        ]);
                    } else {
                        $childArr[] = [
                            'type' => 'view',
                            'name' => $child['title'],
                            'url'  => $child['content'],
                        ];
                    }
                }
                $temp['sub_button'] = $childArr;
                $menuArr[] = $temp;
            } else {
                $eventKey = 'custom_key_' . $item['id'];
                $menuArr[] = [
                    'type' => 'click',
                    'name' => $parentTitle,
                    'key'  => $eventKey,
                ];
                \App\Models\WechatMenu::query()->where('id', $item['id'])->update([
                    'custom_key' => $eventKey,
                ]);
            }
        }
        $config = config('wechat.offical');
        $app = Factory::officialAccount($config);
        $result = $app->menu->create($menuArr);
        if (isset($result['errcode']) && $result['errcode'] == 0) {
            \App\Models\WechatMenu::query()->where('is_del', 0)->where('pid', 0)
                ->where('state', 1)->update([
                    'is_publish' => 1,
                ]);
            foreach ($menuList as $menu) {
                if (!empty($menu['children'])) {
                    foreach ($menu['children'] as $c) {
                        \App\Models\WechatMenu::query()->where('id', $c['id'])->update([
                            'is_publish' => 1,
                        ]);
                    }
                }
            }
            admin_success('发布成功');
        } else {
            admin_error($result['errmsg'] ?? '发布失败');
        }

        return back();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->textarea('current_menu', __('当前配置菜单'))->disable();
        $this->textarea('remark', __('备注'))->disable();
    }

    /**
     * The data of the form.
     *
     * @return array $data
     */
    public function data()
    {
        $config = config('wechat.offical');
        $app = Factory::officialAccount($config);
        $rule = $app->menu->current();
        return [
            'current_menu' => $rule,
            'remark'       => '本次将对菜单进行全量发布，请先确认菜单是否配置正确？',
        ];
    }
}
